//
//  ResourceLoader.swift
//  MySDK
//
//  Created by ifun on 2025/4/23.
//

import UIKit

class MLResourceLoader: NSObject {
    // MARK: - 私有属性
        
        /// 静态库资源 bundle
                private static var resourceBundle: Bundle? {
            let myBundle = Bundle(for: MLResourceLoader.self)
            return myBundle.url(forResource: "MLResources", withExtension: "bundle")
                .flatMap { Bundle(url: $0) }
        }
        
        // MARK: - 公共方法
        
        /// 从静态库 bundle 加载 View XIB
        /// - Parameters:
        ///   - name: XIB 文件名（不包含扩展名）
        ///   - owner: File's Owner
        ///   - type: 视图类型
        /// - Returns: 加载的视图实例
    public static func loadView<T: UIView>(
        fromXib name: String,
        owner: Any? = nil,
        type: T.Type = T.self
    ) -> T {
        let bundle = resourceBundle ?? Bundle(for: self)
        let nib = UINib(nibName: name, bundle: bundle)
        
        guard let view = nib.instantiate(withOwner: owner, options: nil).first as? T else {
            fatalError("Failed to load \(name).xib as \(T.self)")
        }
        
        return view
    }
        
        /// 从静态库 bundle 加载 ViewController XIB
        /// - Parameters:
        ///   - type: ViewController 类型
        ///   - nibName: 自定义 XIB 文件名（可选，默认使用类名）
        /// - Returns: ViewController 实例
        public static func loadViewController<T: UIViewController>(
            _ type: T.Type,
            nibName: String? = nil
        ) -> T {
            let className = String(describing: type)
            let bundle = resourceBundle ?? Bundle(for: type)
            let xibName = nibName ?? className
            
            // 检查 XIB 文件是否存在
            if bundle.path(forResource: xibName, ofType: "nib") != nil {
                return T(nibName: xibName, bundle: bundle)
            }
            
            // 如果没有 XIB，使用默认初始化
            return T()
        }
        
        /// 从 Storyboard 加载 ViewController
        /// - Parameters:
        ///   - storyboardName: Storyboard 文件名（不包含扩展名）
        ///   - identifier: ViewController 的 Storyboard ID（可选，不传则加载 initial）
        ///   - type: ViewController 类型
        /// - Returns: ViewController 实例
        public static func loadViewController<T: UIViewController>(
            fromStoryboard storyboardName: String,
            identifier: String? = nil,
            type: T.Type = T.self
        ) -> T {
            let bundle = resourceBundle ?? Bundle(for: type)
            let storyboard = UIStoryboard(name: storyboardName, bundle: bundle)
            
            if let identifier = identifier {
                guard let vc = storyboard.instantiateViewController(withIdentifier: identifier) as? T else {
                    fatalError("Failed to load \(identifier) from \(storyboardName).storyboard as \(T.self)")
                }
                return vc
            }
            
            guard let vc = storyboard.instantiateInitialViewController() as? T else {
                fatalError("Failed to load initial view controller from \(storyboardName).storyboard as \(T.self)")
            }
            
            return vc
        }
        
    /// 注册XIB cell到tableView
        public static func registerCellXib(for tableView: UITableView, cellClass: AnyClass) {
            let className = String(describing: cellClass)
            let bundle = resourceBundle ?? Bundle(for: cellClass)
            
            // 检查XIB文件是否存在
            if bundle.path(forResource: className, ofType: "nib") != nil {
                let nib = UINib(nibName: className, bundle: bundle)
                tableView.register(nib, forCellReuseIdentifier: className)
            } else {
                tableView.register(cellClass, forCellReuseIdentifier: className)
            }
        }
        
    /// 从tableView获取cell
    public static func dequeueCell<T: UITableViewCell>(from tableView: UITableView, for indexPath: IndexPath) -> T {
        let className = String(describing: T.self)
        guard let cell = tableView.dequeueReusableCell(withIdentifier: className, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(className)")
        }
        return cell
    }
    
    
    
    public static func registerColletionViewCellXib(for collectionView: UICollectionView, cellClass: AnyClass) {
        let className = String(describing: cellClass)
        let bundle = resourceBundle ?? Bundle(for: cellClass)
        
        // 检查XIB文件是否存在
        if bundle.path(forResource: className, ofType: "nib") != nil {
            let nib = UINib(nibName: className, bundle: bundle)
            collectionView.register(nib, forCellWithReuseIdentifier: className)
        } else {
            collectionView.register(cellClass, forCellWithReuseIdentifier: className)
        }
    }
    
    /// 从tableView获取cell
    public static func dequeueCollectionViewCell<T: UICollectionViewCell>(from collectionView: UICollectionView, for indexPath: IndexPath) -> T {
        let className = String(describing: T.self)
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: className, for: indexPath) as? T else {
            fatalError("Could not dequeue cell with identifier: \(className)")
        }
        return cell
    }
    
    
    public static func getBundleFile(name:String,type:String) -> URL?{

        let bundle = resourceBundle ?? Bundle(for: self)
        guard let fileUrl = bundle.url(forResource: name, withExtension: type) else{
//            ml_showLog("未找到文件 \(name)")
            return nil
        }
        return fileUrl
    }
    
    public static func getBundlePathFile(name:String,type:String) -> String?{
        
        let bundle = resourceBundle ?? Bundle(for: self)
        
        guard let filePath = bundle.path(forResource: name, ofType: type) else{
//            ml_showLog("未找到文件\(name)")
            return nil
        }
        
        return filePath
    }
    
    
        /// 加载图片资源
        /// - Parameter name: 图片名称
        /// - Returns: UIImage 实例
    public static func loadImage(named name: String) -> UIImage? {
        
        return UIImage(named: name, in: resourceBundle, compatibleWith: nil)
    }
    

}
